package cn.softeem.tushu.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;

public class GetRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    private String encoding;

    public GetRequest(HttpServletRequest request, String encoding) {
        super(request);
        this.request = request;
        this.encoding = encoding;
    }


    @Override
    public String getParameter(String name) {
        String value = request.getParameter(name);
        if (value != null) {
            try {
                return new String(value.getBytes("iso-8859-1"), encoding);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> map = request.getParameterMap();
        Set<String> keys = map.keySet();
        for (String key : keys) {
            String[] values = map.get(key);
            for (int i = 0; i < values.length; i++) {
                try {
                    values[i] = new String(values[i].getBytes("iso-8859-1"), encoding);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            try {
                values[i] = new String(values[i].getBytes("iso-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return values;
    }
}